package com.zmx.gateway.filter;

import com.zmx.gateway.contents.ReceiverContents;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 记录所有请求日志
 * @ClassName: SendRequestLogListener
 * @Author zhaomxr
 * @Date 2021-11-12 15:17
 */
@Slf4j
@Component
public class SendRequestLog {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Async
    public void send(String requestUrl, String cookies) {
        try {
            if (StringUtils.isEmpty(cookies)) {
                return;
            }

            //如果都通过则放入rabbit消息队列中，记录访问日志
            Map<String, Object> data = new HashMap<String, Object>(5);
            data.put("requestUrl", requestUrl);

            String[] cookieList = cookies.split("; ");
            Map<String, String> cookieMap = new HashMap<String, String>(cookieList.length);
            Arrays.stream(cookieList).forEach(s -> {
                String[] split = s.split("=");
                if (!cookieMap.containsKey(split[0])) {
                    cookieMap.put(split[0], split[1] == null ? null : split[1].trim());
                }
            });
            data.put("token", cookieMap.get("token"));
            data.put("userId", cookieMap.get("userId"));
            data.put("userName", cookieMap.get("userName"));
            data.put("createTime", String.valueOf(System.currentTimeMillis()));
            amqpTemplate.convertAndSend(ReceiverContents.SAVE_REQUEST_LOG_EXCHANGE, "", data);
        } catch (AmqpException e) {
            log.error(e.getMessage(), e);
        }
    }

}
